import React from 'react';
import { Typography } from 'antd';
import { TypographyProps } from 'antd/lib/typography/Typography';

export interface ExpandableTextProps extends TypographyProps {
    rows?: number;
    expandable?: boolean;
    onExpand?: (expand: boolean) => {};
}

const ExpandableText = ({ rows = 2, expandable = true, children, onExpand, ...rest }: ExpandableTextProps) => {
    // Typography 无法直接控制展开收起状态，因此在切换时重新渲染新组件，就会变成默认的收起状态
    const [type, setType] = React.useState(false);

    // 保存展开的状态，以控制收起按钮的展示
    const [expand, setExpand] = React.useState(false);

    const handleClick = (e: any) => {
        e.preventDefault();
        setType(!type);
        setExpand(false);
        if (onExpand) onExpand(false);
    };

    React.useEffect(() => {
        // hack 去除收缩时的title
        setTimeout(() => {
            const a = document.querySelectorAll('.custom-typography');
            a.forEach(item => {
                // @ts-ignore
                // eslint-disable-next-line no-param-reassign
                if (item?.children[0]?.title) {
                    // @ts-ignore
                    // eslint-disable-next-line no-param-reassign
                    item.children[0].title = '';
                }
            });
        }, 100);
    }, [type, expand]);

    return (
        <Typography.Paragraph
            // @ts-ignore
            onClick={(e: any) => {
                // 点击展开收起时阻止冒泡
                const arr = Array.from(e?.target?.classList);
                if (arr?.includes('ant-typography-expand')) {
                    e.stopPropagation();
                }
            }}
            {...rest}
            key={type ? '1' : '2'}
            className="custom-typography"
            ellipsis={{
                rows,
                expandable,
                onExpand: () => {
                    setExpand(true);
                    if (onExpand) onExpand(true);
                }
            }}
        >
            {expand ? (
                <>
                    {children}
                    <a className="ant-typography-expand" onClick={handleClick}>
                        收起
                    </a>
                </>
            ) : (
                children
            )}
        </Typography.Paragraph>
    );
};

export default ExpandableText;
